package com.realjinge.controller;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.realjinge.config.WeChatConfig;
import com.realjinge.service.CallbackService;
import com.realjinge.tools.XmlTool;
import com.realjinge.utils.SHA1Util;

/**
 * 回调请求控制类
 * 
 * @author realjinge
 *
 */
@Controller
public class CallbackController {
	@Resource
	private CallbackService service;

	/**
	 * 微信公众平台服务器接口配置验证(doGet)
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "realjinge.do", method = RequestMethod.GET)
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 开发者接入验证
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String signature = request.getParameter("signature");
			String echostr = request.getParameter("echostr");

			if (signature.equals(SHA1Util.gen(WeChatConfig.TOKEN, timestamp, nonce))) {
				XmlTool.out(echostr, response);
			} else {
				XmlTool.out("", response);
			}
		} catch (Throwable e) {
			e.printStackTrace();
			XmlTool.out("", response);
		}
	}

	@RequestMapping(value = "realjinge.do", method = RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 编码格式
			request.setCharacterEncoding("UTF-8");

			// 验证签名
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String signature = request.getParameter("signature");
			if (!signature.equals(SHA1Util.gen(WeChatConfig.TOKEN, timestamp, nonce))) {
				XmlTool.out("", response);
				return;
			}

			// 解析XML
			Map<String, String> reqMap = XmlTool.parseXml(request.getInputStream());
			System.out.println("reqMap=" + reqMap);

			// 处理请求
			String xmlStr = service.handle(reqMap);

			System.out.println("xmlStr=" + xmlStr);

			// null 转为空字符串
			xmlStr = xmlStr == null ? "" : xmlStr;

			XmlTool.out(xmlStr, response);
		} catch (Throwable e) {
			e.printStackTrace();
			// 异常时响应空串
			XmlTool.out("", response);
		}
	}

}
